package com.pelli.imarket.client.widget;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.gwtext.client.util.JSON;
import com.gwtext.client.widgets.PagingToolbar;
import com.pelli.imarket.client.store.JsonModelData;

public class GridManager {

	/**
	 * 
	 * @param workbench La finestra del browser
	 * @param gridContainer Il pannello contenitore della griglia in cui essa va ggiunta e rimossa
	 * @param idGrid Id della griglia all'interno del contesto
	 */
	public static void generateGrid(final ContentPanel workbench,
			final ContentPanel gridContainer, String idGrid) {
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
				"grid.xml");
		try {
			builder.setHeader("tableName", idGrid);
			builder.setCallback(new RequestCallback() {
				
				@Override
				public void onResponseReceived(Request request,
						Response response) {
					// TODO Auto-generated method stub
					final JSONObject json = new JSONObject(JSON.decode(response
							.getText()));
					JSONValue store = json.get("store");
					JSONValue remote = json.get("remote");
					final ListStore<JsonModelData> stores = new ListStore<JsonModelData>();
					final List<JsonModelData> datas = new ArrayList<JsonModelData>();
					if (store.isString() != null) {
//						System.out.println("Store: "
//								+ store.isString().stringValue());

						RequestBuilder rb = new RequestBuilder(
								RequestBuilder.GET, "invoke.rest");
						rb.setHeader("restURL", store.isString().stringValue());
						rb.setHeader("remote", remote.isString().stringValue());
						rb.setCallback(new RequestCallback() {

							@Override
							public void onResponseReceived(Request request,
									Response res) {
								JSONArray rows = new JSONArray(JSON.decode(res
										.getText()));
								for (int i = 0; i < rows.size(); i++) {
									JSONObject row = rows.get(i).isObject();
									datas.add(new JsonModelData(row));
								}

								JSONArray columns = (JSONArray) json
										.get("columns");
								List<ColumnConfig> cc = new ArrayList<ColumnConfig>();
								for (int i = 0; i < columns.size(); i++) {
									JSONObject column = (JSONObject) columns
											.get(i);
									ColumnConfig columnConfig = new ColumnConfig();
									columnConfig.setId(column.get("id")
											.isString().stringValue());
									columnConfig.setHeader(column.get("name")
											.isString().stringValue()
											.toUpperCase());
									columnConfig.setWidth(200);
									cc.add(columnConfig);
								}
								Iterator<Component> components = gridContainer
										.iterator();
								EditorGrid oldGrid = null;
								while (components.hasNext()) {
									Component component = (Component) components
											.next();
									if (component instanceof Grid) {
										EditorGrid g = (EditorGrid) component;
										if (g.getId().equals("GRID_DATA_ENTRY")) {
											oldGrid = g;
											break;
										}
									}
								}
								gridContainer.remove(oldGrid);
								// ListStore<JsonModelData>
								stores.add(datas);
								EditorGrid grid = new EditorGrid(stores,
										new ColumnModel(cc));

								grid.setId("GRID_DATA_ENTRY");
								
								
								gridContainer.add(grid, new BorderLayoutData(
										LayoutRegion.CENTER));

								grid.setBorders(true);
								workbench.layout(true);
							}

							@Override
							public void onError(Request request,
									Throwable exception) {
								// TODO Auto-generated method stub

							}
						});
						try {
							rb.send();
						} catch (RequestException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				}

				@Override
				public void onError(Request request, Throwable exception) {
					// TODO Auto-generated method stub
					System.out
							.println("HomePanel.HomePanel().new TreePanelSelectionModel() {...}.onMouseClick(...).new RequestCallback() {...}.onError()");
				}
			});
			builder.send();
		} catch (RequestException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
//		System.out.println(builder.getRequestData());
//		System.out.println("<========");

		// Grid grid = GridFactory.createGrid(em.getId(),new
		// ListStore());
		//
		// secondPanel.add(grid, new
		// BorderLayoutData(LayoutRegion.CENTER));
		// grid.setBorders(true);
		// mainPanel.layout(true);
	}
}
